import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/app/prisma/client';
import getUserId from '@/utils/getUserId';

export async function POST(req: NextRequest, { params }: { params: { id: string } }) {
  const userId = getUserId(req);
  if (!userId) {
    return NextResponse.json({ error: '请先登录' }, { status: 401 });
  }

  const blockedUserId = params.id;

  if (userId === blockedUserId) {
    return NextResponse.json({ error: '不能拉黑自己' }, { status: 400 });
  }

  try {
    await prisma.block.create({
      data: { userId, blockedUserId },
    });
    return NextResponse.json({ message: '已拉黑该用户' });
  } catch (e: any) {
    if (e.code === 'P2002') {
      // P2002 is for unique constraint violations. If it already exists, we can treat it as a success.
      return NextResponse.json({ message: '已拉黑该用户' });
    }
    return NextResponse.json({ error: '拉黑失败', detail: e.message }, { status: 500 });
  }
}

export async function DELETE(req: NextRequest, { params }: { params: { id: string } }) {
  const userId = getUserId(req);
  if (!userId) {
    return NextResponse.json({ error: '请先登录' }, { status: 401 });
  }

  const blockedUserId = params.id;

  await prisma.block.deleteMany({
    where: { userId, blockedUserId },
  });

  return NextResponse.json({ message: '已取消拉黑' });
}
